package com.study.postprocessor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;

//bean工厂后处理器
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
//        1.修改原有Bean的实现类
//        System.out.println("MyBeanFactoryPostProcessor执行了...");
//        BeanDefinition userDaoBD = configurableListableBeanFactory.getBeanDefinition("userDao");
//        userDaoBD.setBeanClassName("com.study.dao.impl.UserDaoImpl2");
        //2.对Bean进行注册
        //强转成子类DefaultListableBeanFactory
        if (configurableListableBeanFactory instanceof DefaultListableBeanFactory) {
            DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)configurableListableBeanFactory;
            BeanDefinition beanDefinition = new RootBeanDefinition();
            beanDefinition.setBeanClassName("com.study.dao.impl.UserDaoImpl2");
            //进行注册操作
            beanFactory.registerBeanDefinition("userDao2",beanDefinition);
        }
    }
}
